package com.ByteDance.controller;


import com.ByteDance.model.po.UserInfos;
import com.ByteDance.model.po.VideoEntity;
import com.ByteDance.model.vo.*;
import com.ByteDance.service.IFavoriteService;
import com.ByteDance.service.IUserService;
import com.ByteDance.service.IVideoService;
import com.ByteDance.utils.AliOSSUtils;
import com.ByteDance.utils.JwtUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.ibatis.ognl.Token;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * <p>
 * 视频表 前端控制器
 * </p>
 *
 * @author 朱哥
 * @since 2024-02-25
 */
@Api(tags = "PublishController")
@RestController
@RequestMapping("/douyin/publish")
@RequiredArgsConstructor
public class PublishController {
    private final IFavoriteService iFavoriteService;
    private final IUserService iUserService;

    private final IVideoService iVideoService;
    private final AliOSSUtils aliOSSUtils;

    @Value("${video-config.video-save-path}")
    private String VIDEO_PATH;

    @Value("${video-config.video-cover-save-path}")
    private String VIDEO_COVER_PATH;
    //静态常量
    private static final String DEFAULT_VIDEO_FORMAT = ".mp4";
    private static final String DEFAULT_IMG_FORMAT = ".jpg";
    @ApiOperation("用户投稿接口")
    @PostMapping("/action")
    public ActionVO action(@RequestParam(value = "data")MultipartFile data, @RequestParam(value = "title")String title, HttpServletRequest req) throws Exception {
        if (StringUtils.isEmpty(title) || data.isEmpty() || data.getSize() == 0) {
            return ActionVO.fail();
        }
        //能成功访问到该接口，就可以直接获取jwt中的声明信息
        int userId = JwtUtils.getUserId(req.getHeader("token"));//获取userId到时候保存信息的时候用
        //将接收到的视频上传到阿里云OSS，视频数据和标题进行保存
        //先构建video的fileTargetPath
        String video = VIDEO_PATH + "/" + UUID.randomUUID().toString() + DEFAULT_VIDEO_FORMAT;
        String videoPath = aliOSSUtils.upload(video, data);
        //截取视频的一帧作为封面，并上传
        String cover = VIDEO_COVER_PATH + "/" + UUID.randomUUID().toString() + DEFAULT_IMG_FORMAT;
        String coverPath = iVideoService.uploadCover(cover, videoPath, DEFAULT_IMG_FORMAT);
        //将数据进行保存到Video视频表
        iVideoService.saveVideoMsg(userId,videoPath,coverPath,title);
        //构建ActionVO
        ActionVO actionVO = ActionVO.success();
        return actionVO;
    }

    /**
     * 登录用户的视频发布列表，直接列出用户所有投稿过的视频。(查看自己的)
     * 实际上是可以设计观看别的用户的作品的(但涉及权限-公开-朋友-私有-部分可见-指定不可见)
     * @param userId
     * @return
     */
    @ApiOperation("用户视频发布列表接口")
    @GetMapping("/list")
    public PublishVO list(@RequestParam(value = "user_id") Integer userId){
        if(StringUtils.isEmpty(userId)){
            return PublishVO.fail();
        }
        //查询当前用户信息
        UserInfos author = iUserService.getById(userId);
        User user = new User();
        user.setUserId(userId);
        user.setUsername(author.getUsername());
        user.setFollowCount(author.getFollowCount());
        user.setFollowerCount(author.getFollowerCount());
        //自己不用关注自己
        user.setFollow(false);
        user.setAvatar(author.getAvatar());
        user.setBackgroundImage(author.getBackgroundImage());
        user.setSignature(author.getSignature());
        user.setTotalFavorited(author.getTotalFavorited());
        user.setWorkCount(author.getWorkCount());
        user.setFavoriteCount(author.getFavoriteCount());
        //返回一个List<VideoEntity> videoEntity
        List<VideoEntity> list = iVideoService.searchVideosByUserId(userId);

        Video[] videos = new Video[list.size()];
        //遍历List，然后构造Video,存入Video[]数组中
        for (int i = 0; i < list.size(); i++) {
            VideoEntity videoEntity = list.get(i);
            videos[i] = new Video();
            videos[i].setId(videoEntity.getVideoId());
            videos[i].setAuthor(user);
            videos[i].setCommentCount(videoEntity.getCommentCount());
            videos[i].setPlayurl(videoEntity.getPlayUrl());
            videos[i].setCoverurl(videoEntity.getCoverUrl());
            videos[i].setFavoriteCount(videoEntity.getFavoriteCount());
            //得查看是否点赞了自己的视频
            boolean flag = iFavoriteService.isFavorite(videoEntity.getVideoId(), userId);
            if(flag){
                videos[i].setFavorite(true);
            }else {
                videos[i].setFavorite(false);
            }

            videos[i].setTitle(videoEntity.getTitle());
        }

        PublishVO publishVO = PublishVO.success();
        publishVO.setVideoList(videos);
        //构造PublishVO
        return publishVO;
    }

}
